/**
 * 
 */
package org.mhz.ootw.dataaccess;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.mhz.ootw.annotation.LogTimeTaken;
import org.mhz.ootw.entity.ReadableContent;
import org.mhz.ootw.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Mahan
 *
 * Repository contents DAO
 */
@Repository(Constants.REPOSITORY_CONTENTS_DAO)
@Transactional
public class RepositoryContentsDAO
{
    private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryContentsDAO.class);    
    
    @Resource(name = Constants.SESSION_FACTORY)
    private SessionFactory mSessionFactory;
    
    /**
     * Retrieves all the contents
     * 
     * @param aNodeId - The node id
     * @return The contents as a list
     */
    @LogTimeTaken
    public List<ReadableContent> getAll(final String aNodeId) 
    {
        // Retrieve session from Hibernate
        final Session session = mSessionFactory.getCurrentSession();
        
        // Get the location of the contents
        final String locationSql = "SELECT node_content_location FROM menu_hierarchy_t where node_id = '" + aNodeId + "'";
        
        final String location = (String) session.createSQLQuery(locationSql).uniqueResult();
        
        // Get the contents from the location
        final String sql = "SELECT id, content from " + location + " order by id";
        
         // Create a Hibernate native SQL query
        final Query query = session.createSQLQuery(sql).addEntity(ReadableContent.class);
        
        // Retrieve all
        return  query.list();
    }     
}
